#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <stdio.h>

#include<iostream>
#include <gst/gst.h>
#include <stdio.h>

#include <sstream>
#include <string>

using namespace std;

string audioPath;
char actual_song[200];
GstElement *pipeline;
gint64 pos, len;


/*int cb_print_position ()
{
  GstFormat g_form = GST_FORMAT_TIME;
  if (gst_element_query_position (pipeline, &g_form, &pos)
    && gst_element_query_duration (pipeline, &g_form, &len)) {
    g_print ("Time: %" GST_TIME_FORMAT " / %" GST_TIME_FORMAT "\r",
         GST_TIME_ARGS (pos), GST_TIME_ARGS (len));
    return pos/GST_SECOND;
  }

  /* call me again
  return 0;
}*/
void sendMp3Audio ()
{

    /*Main object*/
   // GMainLoop *loop;

    /*Elements*/
    GstElement *source,
                *mad,
                //*pipeline,
                *convert,
                *rtp, /* RTP packer */
                *udp; /* UDP sender */



    char *audioFileName = (char*)malloc(1024*sizeof(char));
    //int change_volumen;

    strcpy(audioFileName, audioPath.c_str());
    strcpy(actual_song, audioPath.c_str());




    //loop = g_main_loop_new (NULL, FALSE);


    /* Create gstreamer elements */
    pipeline = gst_pipeline_new ("mp3 player");
    source = gst_element_factory_make ("filesrc", "filesrc");

    /* we set the input filename to the source element */
    g_object_set (G_OBJECT (source), "location", audioFileName , NULL);

    mad = gst_element_factory_make ("mad", "mad");
    convert = gst_element_factory_make("audioconvert", NULL);

    rtp = gst_element_factory_make("rtpL16pay", "rtpL16pay");
    udp = gst_element_factory_make("udpsink", "udpsink");

    g_object_set( udp, "host", "192.168.16.102", "port", 5000, NULL );



    if (!pipeline || !source || !mad || !convert || !rtp || !udp) {
            g_printerr ("One element could not be created. Exiting.\n");
            //return -1;
        }

    /* we add all elements into the pipeline */
    gst_bin_add_many(GST_BIN(pipeline), source, mad, convert, rtp, udp, NULL);

    /* we link the elements together */
    gst_element_link_many (source, mad, convert, rtp, udp, NULL);

    /* Set the pipeline to "playing" state*/
    g_print ("Now playing: %s\n", audioFileName);
    gst_element_set_state (pipeline, GST_STATE_PLAYING);

    /* Iterate */
    //g_print ("Running...\n");
    //g_main_loop_run (loop);

    /* Stop playback */
    //g_print ("Stopping playback\n");
    //gst_element_set_state (pipeline, GST_STATE_NULL);

    /* Delete the pipeline */
    //g_print ("Deleting pipeline\n");
    //gst_object_unref (GST_OBJECT (pipeline));
    //g_main_loop_unref (loop);


}

void playMp3Audio()
{
    /*Main object*/
    //GMainLoop *loop;

    /*Elements*/
    GstElement *source,
                *mad,
                //*pipeline,
                //*volumen,
                *output; /* audio output */


    char *audioFileName = (char*)malloc(1024*sizeof(char));

    strcpy(audioFileName, audioPath.c_str());
    strcpy(actual_song, audioPath.c_str());

   // loop = g_main_loop_new (NULL, FALSE);


    /* Create gstreamer elements */
    pipeline = gst_pipeline_new ("mp3 player");
    source = gst_element_factory_make ("filesrc", "filesrc");

    /* we set the input filename to the source element */
    g_object_set (G_OBJECT (source), "location", audioFileName , NULL);

    mad = gst_element_factory_make ("mad", "mad");

    //volumen = gst_element_factory_make ("volume", "volume");

    //g_object_set (G_OBJECT (volumen), "volume", 5, NULL);

    output = gst_element_factory_make("alsasink", "alsasink");



    if (!pipeline || !source || !mad || !output) {
            g_printerr ("One element could not be created. Exiting.\n");
            //return -1;
        }

    /* we add all elements into the pipeline */
    gst_bin_add_many(GST_BIN(pipeline), source, mad, output, NULL);

    /* we link the elements together */
    gst_element_link_many (source, mad, output, NULL);

    /* Set the pipeline to "playing" state*/
    g_print ("Now playing: %s\n", audioFileName);
    gst_element_set_state (pipeline, GST_STATE_PLAYING);

    /* Iterate */
    //g_print ("Running...\n");
    //g_main_loop_run (loop);

    /* Stop playback */
    //g_print ("Stopping playback\n");
    //gst_element_set_state (pipeline, GST_STATE_NULL);

    /* Delete the pipeline */
    //g_print ("Deleting pipeline\n");
    //gst_object_unref (GST_OBJECT (pipeline));
    //g_main_loop_unref (loop);


}

void stop_audio ()
{
    gst_element_set_state (pipeline, GST_STATE_PAUSED);
    gst_element_set_state (pipeline, GST_STATE_NULL);
    g_print ("Deleting pipeline\n");
    gst_object_unref (GST_OBJECT (pipeline));




}


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /* All this creates the File Browser*/
    QString sPath = "/media/sda1/Musica";
    audioPath = (char*)malloc(1024*sizeof(char));
    dirmodel = new QFileSystemModel(this);
    dirmodel->setRootPath(sPath);
    ui->treeView->setModel(dirmodel);
    //QObject::connect(ui->spinBox,SIGNAL(valueChanged(int)),ui->dial,SLOT(setValue(int)));
    //QObject::connect(ui->dial,SIGNAL(valueChanged(int)),ui->spinBox,SLOT(setValue(int)));


}

MainWindow::~MainWindow()
{
    delete ui;

}

/*This method executes when a file is selected in the File Browser*/
void MainWindow::on_treeView_clicked(const QModelIndex &index)
{
    QString filePath = dirmodel->fileInfo(index).absoluteFilePath();
    QByteArray byteArray = filePath.toUtf8();
    audioPath = string(byteArray.data()); //Gets the path of the file selected

    cout <<"\nThe File Path is " << audioPath << endl; //Prints the file path

}


/* This method executes when the Stop button is pressed*/
void MainWindow::on_buttonStop_clicked()
{
    cout <<"\nStop Audio" << endl;
    ui->label_4->setText("Seleccione la cancion");
    stop_audio();
}


/* This method executes when the Play button is pressed*/
void MainWindow::on_buttonPlay_clicked()
{

    if(ui->radioButtonClient->isChecked()){
        cout <<"\nSending audio to the Client" << endl;
        stop_audio();
        sendMp3Audio();
    }
    else if(ui->radioButtonBB->isChecked()){
        cout <<"\nSending audio to the Beagle Board XM" << endl;
        stop_audio();
        playMp3Audio();
    }

    ui->label_4->setText(actual_song);

}

